package action

import (
	//"time"
	"crypto/md5"
	"encoding/hex"
	"errors"
	. "etrgo"
	"github/session"
	_ "github/session/providers/memory"
	"strconv"
	"strings"
)

var globalSessions *session.Manager

const (
	SID = "sid"
)

var NoSuchUser = errors.New("no such user")
var AuthFail = errors.New("authentication failed.")

func init() {
	globalSessions, _ = session.NewManager("memory", SID, 3600)
	go globalSessions.GC()
}

func AuthUser(user string, passwd string) (bool, error) {
	db := GetDB()
	var md5passwd string
	err := db.QueryRow("select passwd from admin where name = ? ", user).Scan(&md5passwd)
	if err == nil {
		h := md5.New()
		h.Write([]byte(passwd))
		newmd5psswd := hex.EncodeToString(h.Sum(nil))
		if strings.EqualFold(md5passwd, newmd5psswd) {
			return true, nil
		} else {
			return false, AuthFail
		}
	} else {
		return false, NoSuchUser
	}
	return false, nil
}

func AuthFilter(action Action) bool {
	Debug("auth the current session")
	sess := globalSessions.SessionStart(action.ResponseWriter, action.Request)
	sid := sess.Get(SID)
	Info("session :%s", sess.SessionID())
	if sid != nil {
		Info("session exist")
		return false
		//Info("new a session[%s]",sid)
	} else {
		Info("session not exist and set it")
		sess.Set(SID, sess.SessionID())
		return true
		//Debug("sid is %s,session=%s.",sid,sess.SessionID())
	}
	return true
}

func SecurityCodeAction(action Action) {
	d := make([]byte, 4)
	s := NewLen(4)
	ss := ""
	d = []byte(s)
	for v := range d {
		d[v] %= 10
		ss += strconv.FormatInt(int64(d[v]), 32)
	}
	action.ResponseWriter.Header().Set("Content-Type", "image/png")
	NewImage(d, 100, 40).WriteTo(action.ResponseWriter)
	Debug("the security code of the current session:%s", ss)
	globalSessions.SessionStart(action.ResponseWriter, action.Request).Set("scode", ss)
	//fmt.Println(ss)
}
